import {defineStore} from "pinia";
// @ts-ignore
import {ajax, requestCache} from "@/js/api_tool.js";
// @ts-ignore
import {cacheGet, cacheSet} from "@/store/pluginCache.js";

export const use_this_user = defineStore('this_user', {
    state: () => {
        return {
            id: 0,
            parent_id: 0,
            parent_id_path: ",0,",
            max_level_parent_id: 0,
            phone: "",
            nickname: "",
            truename: "",
            head_img: "",
            sex: 0,
            info: "",
            level: 0,
            money: 0,
            score_level: 0,
            score_status: 1,
            openid: "{}",
            territory_area_id: 0,
            province_area_id: 0,
            city_area_id: 0,
            county_area_id: 0,
            town_area_id: 0,
            token: "",
            vip_expiration_time: "1970-01-01 00:00:00",
            extend: "{}",
            disabled: 0,
            last_time: null,
            last_ip: null,
            origin_tenant_id: 0,
            create_time: "",
            delete_time: 0,
            tenant_id: 0,
            status: "",
            level_name: "",
        }
    },
    actions: {
        /**通过请求接口，获取数据后合并，来刷新数据
         */
        async refresh(){
            try {
                let {data} = await ajax({url: '/home/user/session_info', showMessage: ajax.SHOW_MESSAGE_NONE});
                if (!data){
                    // 未登陆的清空
                    return this.$reset();
                }
                let old = cacheGet(this.$id);
                const old_json = JSON.stringify(old);
                const data_json = JSON.stringify(data);
                if (old_json !== data_json){
                    console.log(`refresh ${this.$id} ok`)
                    this.$patch(data);
                    cacheSet(this.$id, data);
                }
            } catch (e:any) {
                console.log(`refresh fail: ${e.message || e}`)
            }
        },
    }
})
